//
//  FicowStepper.m
//  FicowStepper
//
//  Created by ficow on 16/3/17.
//  Copyright © 2016年 ficow. All rights reserved.
//

// action control: UIControlEventApplicationReserved for increment/decrement?
// delegate: if there are multiple FicowSteppers in one viewcontroller, it will be a hassle to identify each FicowSteppers
// block: watch out for retain cycle

// check visibility of buttons when
// 1. right before displaying for the first time
// 2. value changed
#import "FicowStepper.h"

@interface FicowStepper()<UITextFieldDelegate>

@end

@implementation FicowStepper{
    CGFloat fWidth;
    CGFloat fHeight;
    CGRect fCountFieldFrame;
    CGRect fIncrementButtonFrame;
    CGRect fDecrementButtonFrame;
}

#pragma mark --- initialization ---
- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame])
    {
        [self commonInit];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super initWithCoder:aDecoder])
    {
        [self commonInit];
    }
    return self;
}

- (void)commonInit
{
    _value = 1;
    _stepInterval = 1;
    _minimum = 0;
    _maximum = 100;
    _hidesDecrementWhenMinimum = YES;
    _hidesIncrementWhenMaximum = YES;
    
    [self setFieldFont:[UIFont fontWithName:@"Avernir-Roman" size:14.0f]];
    [self setButtonFont:[UIFont fontWithName:@"Avenir-Black" size:24.0f]];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(checkCountFieldTextLength:)
                                                 name:UITextFieldTextDidChangeNotification
                                               object:self.countField];
}

#pragma mark -- Observe the Field --
- (void)checkCountFieldTextLength:(id)sender {
    if (self.countField.text.intValue > self.maximum) {
        self.countField.text = [NSString stringWithFormat:@"%d",self.maximum];
    }
    if (self.countField.text.intValue < self.minimum) {
        self.countField.text = [NSString stringWithFormat:@"%d",self.minimum];
    }
    self.value = self.countField.text.intValue;
}

#pragma mark --- render ---
- (void)layoutSubviews
{    
    self.countField.frame = fCountFieldFrame;
    self.incrementButton.frame = fIncrementButtonFrame;
    self.decrementButton.frame =fDecrementButtonFrame;
    
    self.incrementButton.hidden = (self.hidesIncrementWhenMaximum && [self isMaximum]);
    self.decrementButton.hidden = (self.hidesDecrementWhenMinimum && [self isMinimum]);
}

- (void)setup
{
    if (self.valueChangedCallback)
    {
        self.valueChangedCallback(self, self.value);
    }
}

- (void)setDefaultStyle:(FicowStepperStyle)style {
    
    self.clipsToBounds = YES;
    switch (style) {
        case FicowStepperStyleDefault1: {
            [self setDefaultStyleWithStyleOne];
            break;
        }
        case FicowStepperStyleDefault2: {
            [self setDefaultStyleWithStyleTwo];
            break;
        }
        case FicowStepperStyleDefault3: {
            [self setDefaultStyleWithStyleThree];
            break;
        }
        default:
            [self setDefaultStyleWithStyleOne];
            break;
    }
    self.incrementButton.showsTouchWhenHighlighted = YES;
    self.decrementButton.showsTouchWhenHighlighted = YES;
}

- (CGSize)sizeThatFits:(CGSize)size
{
    if (CGSizeEqualToSize(size, CGSizeZero))
    {
        // if CGSizeZero, return ideal size
        CGSize FieldSize = [self.countField sizeThatFits:size];
        return CGSizeMake(FieldSize.width + (self.buttonWidth * 2), FieldSize.height);
    }
    return size;
}


#pragma mark --- view customization ---
- (void)setBorderColor:(UIColor *)color
{
    self.layer.borderColor = color.CGColor;
}

- (void)setTextFieldBorderColor:(UIColor*)color{
    self.countField.layer.borderColor = color.CGColor;
}

- (void)setBorderWidth:(CGFloat)width
{
    self.layer.borderWidth = width;
}

- (void)setCornerRadius:(CGFloat)radius
{
    self.layer.cornerRadius = radius;
}

- (void)setFieldTextColor:(UIColor *)color
{
    self.countField.textColor = color;
}

- (void)setFieldFont:(UIFont *)font
{
    self.countField.font = font;
}

- (void)setButtonTextColor:(UIColor *)color forState:(UIControlState)state
{
    [self.incrementButton setTitleColor:color forState:state];
    [self.decrementButton setTitleColor:color forState:state];
}

- (void)setButtonFont:(UIFont *)font
{
    self.incrementButton.titleLabel.font = font;
    self.decrementButton.titleLabel.font = font;
}

#pragma mark --- setter ---
- (void)setValue:(int)value
{
    _value = value;
    if (self.hidesDecrementWhenMinimum)
    {
        self.decrementButton.hidden = [self isMinimum];
    }
    
    if (self.hidesIncrementWhenMaximum)
    {
        self.incrementButton.hidden = [self isMaximum];
    }
    
    if (self.valueChangedCallback)
    {
        self.valueChangedCallback(self, _value);
    }
}

#pragma mark --- event handler ---
- (void)incrementButtonTapped:(id)sender
{
    if (self.value < self.maximum)
    {
        self.value += self.stepInterval;
        if (self.incrementCallback)
        {
            self.incrementCallback(self, self.value);
        }
    }
}

- (void)decrementButtonTapped:(id)sender
{
    if (self.value > self.minimum)
    {
        self.value -= self.stepInterval;
        if (self.decrementCallback)
        {
            self.decrementCallback(self, self.value);
        }
    }
}

#pragma mark --- private helpers ---
- (BOOL)isMinimum
{
    return self.value == self.minimum;
}

- (BOOL)isMaximum
{
    return self.value == self.maximum;
}

#pragma mark --- Default Styles ---
- (void)setDefaultStyleWithStyleOne{
    _buttonWidth = 44.0f;
    fWidth = self.bounds.size.width;
    fHeight = self.bounds.size.height;
    
    [self setBorderWidth:1.0f];
    [self setCornerRadius:0.0f];
    
    fCountFieldFrame = CGRectMake(self.buttonWidth, 0, fWidth - (self.buttonWidth * 2), fHeight);
    fIncrementButtonFrame = CGRectMake(fWidth - self.buttonWidth, 0, self.buttonWidth, fHeight);
    fDecrementButtonFrame = CGRectMake(0, 0, self.buttonWidth, fHeight);
    
    self.countField = [[UITextField alloc] init];
    self.countField.textAlignment = NSTextAlignmentCenter;
    self.countField.layer.borderWidth = 1.0f;
    [self addSubview:self.countField];
    
    self.incrementButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.incrementButton setTitle:@"+" forState:UIControlStateNormal];
    [self.incrementButton addTarget:self
                             action:@selector(incrementButtonTapped:)
                   forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:self.incrementButton];
    
    
    self.decrementButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.decrementButton setTitle:@"-" forState:UIControlStateNormal];
    [self.decrementButton addTarget:self
                             action:@selector(decrementButtonTapped:)
                   forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:self.decrementButton];
    
    UIColor *defaultColor = [UIColor colorWithRed:(79/255.0)
                                            green:(161/255.0)
                                             blue:(210/255.0)
                                            alpha:1.0];
    [self setBorderColor:defaultColor];
    [self setTextFieldBorderColor:defaultColor];
    [self setFieldTextColor:defaultColor];
    [self setButtonTextColor:defaultColor forState:UIControlStateNormal];
}

- (void)setDefaultStyleWithStyleTwo{
    _buttonWidth = 22.0f;
    
    //suggest frame in common use
    //self.frame = CGRectMake(([UIScreen mainScreen].bounds.size.width - 250) / 2.0, 200, 88, 30);
    fWidth = self.bounds.size.width;
    fHeight = self.bounds.size.height;
    UIFont *fFont = [UIFont systemFontOfSize:12 weight:0.2];
    
    [self setBorderWidth:1.0f];
    [self setCornerRadius:0.0f];
    
    fCountFieldFrame = CGRectMake(self.buttonWidth, 1, fWidth - (self.buttonWidth * 2), fHeight - 2);
    fIncrementButtonFrame = CGRectMake(fWidth - self.buttonWidth, 0, self.buttonWidth, fHeight);
    fDecrementButtonFrame = CGRectMake(0, 0, self.buttonWidth, fHeight);
    
    self.countField = [[UITextField alloc] init];
    self.countField.textAlignment = NSTextAlignmentCenter;
    self.countField.layer.borderWidth = 0.5f;
    self.countField.font = fFont;
    [self addSubview:self.countField];
    
    self.incrementButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.incrementButton setTitle:@"+" forState:UIControlStateNormal];
    [self.incrementButton addTarget:self
                             action:@selector(incrementButtonTapped:)
                   forControlEvents:UIControlEventTouchUpInside];
    self.incrementButton.titleLabel.font = fFont;
    [self addSubview:self.incrementButton];
    
    self.decrementButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.decrementButton setTitle:@"-" forState:UIControlStateNormal];
    [self.decrementButton addTarget:self
                             action:@selector(decrementButtonTapped:)
                   forControlEvents:UIControlEventTouchUpInside];
    self.decrementButton.titleLabel.font = fFont;
    [self addSubview:self.decrementButton];
    
    UIColor *defaultColor = RGB(77, 77, 77, 1);
    [self setBorderColor:[UIColor whiteColor]];
    [self setTextFieldBorderColor:RGB(153, 153, 153, 1)];
    [self setFieldTextColor:defaultColor];
    [self setButtonTextColor:defaultColor forState:UIControlStateNormal];
}

- (void)setDefaultStyleWithStyleThree{
    _buttonWidth = 26.0f;
    
    //suggest frame in common use
    //self.frame = CGRectMake(([UIScreen mainScreen].bounds.size.width - 250) / 2.0, 200, 88, 30);
    fWidth = self.bounds.size.width;
    fHeight = self.bounds.size.height;
    
    [self setBorderWidth:1.0f];
    //[self setCornerRadius:5.0f];
    
    fCountFieldFrame = CGRectMake(self.buttonWidth , 0, fWidth - (self.buttonWidth * 2), fHeight);
    fIncrementButtonFrame = CGRectMake(fWidth - self.buttonWidth, 0, self.buttonWidth, fHeight);
    fDecrementButtonFrame = CGRectMake(0, 0, self.buttonWidth, fHeight);
    
    self.countField = [[UITextField alloc] init];
    self.countField.textAlignment = NSTextAlignmentCenter;
    self.countField.layer.borderWidth = 1.0f;
    [self addSubview:self.countField];
    
    self.incrementButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.incrementButton setTitle:@"+" forState:UIControlStateNormal];
    [self.incrementButton addTarget:self
                             action:@selector(incrementButtonTapped:)
                   forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:self.incrementButton];
    
    self.decrementButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.decrementButton setTitle:@"-" forState:UIControlStateNormal];
    [self.decrementButton addTarget:self
                             action:@selector(decrementButtonTapped:)
                   forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:self.decrementButton];
    
    // color
    [self setBorderColor:[UIColor whiteColor]];
    [self setTextFieldBorderColor:[UIColor whiteColor]];
    [self setFieldTextColor:[UIColor colorWithRed:0.1
                                            green:0.17
                                             blue:0.23
                                            alpha:1]];
    [self.incrementButton setBackgroundColor:[UIColor colorWithRed:0.91
                                                             green:0.91
                                                              blue:0.91
                                                             alpha:1]];
    [self.decrementButton setBackgroundColor:[UIColor colorWithRed:0.91
                                                             green:0.91
                                                              blue:0.91
                                                             alpha:1]];//
    [self setButtonTextColor:[UIColor colorWithRed:0.54
                                             green:0.54
                                              blue:0.54
                                             alpha:1]
                    forState:UIControlStateNormal];
}

#pragma mark --- dealloc ---
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
